/* eslint-disable no-unused-vars */
import React, { useEffect, useRef, useState } from 'react';
import './App.css';

import OnlyOfficeEditor from './components/OnlyOfficeEditor';
import { onlyofficeControllerHtmlStr } from './templatehtmlstr';
import { factorList } from './factorList';

const tokenConfig = {
  "enable": true,
  "useforrequest": true,
  "algorithmRequest": "HS256",
  "authorizationHeader": "Authorization",
  "authorizationHeaderPrefix": "Bearer ",
  "secret": "VI71S3cGtXg96HgFWzQhblz1KwMc1Jzk",
  "expiresIn": 5 * 60 * 1000
};

function App() {

  const [documentUrl, setDocumentUrl] = useState('http://hzero-test-cache.proxy.open-front.hand-china.com/static-files/%E5%90%88%E5%90%8C%E6%B5%8B%E8%AF%95-%E9%87%87%E8%B4%AD%E5%90%88%E5%90%8C.docx');
  // const [documentUrl, setDocumentUrl] = useState('http://hzero-test-cache.proxy.open-front.hand-china.com/static-files/new_9.docx');

  const ooRef = useRef(null);

  window.ooRef = ooRef;

  const handleFileUpload = async () => {

    const fileUrl = window.prompt('请输入一个文件地址 url，支持 word ，rtf', 'http://hzero-test-cache.proxy.open-front.hand-china.com/static-files/%E6%88%90%E7%BB%A9%E8%A1%A8.xlsx')

    if (!fileUrl || !fileUrl.startsWith('http')) {
      return;
    }
    setDocumentUrl(fileUrl);

  };

  const handleExportFile = () => {
    const editor = ooRef.current.getEditor();
    editor.downloadAs('rtf');
    // console.log({editor});
    // const data = editor.downloadAs('rtf');
    // console.log(data);
  };

  // const handleEdiorHello = () => {
  //   const editor = ooRef.current.getEditor();
  //   editor.showMessage("Welcome to ONLYOFFICE Editor!")
  // };

  const config = React.useMemo(() => {
    return {
      // apiUrl: 'http://local.jajabjbj.top',
      // apiUrl: 'http://172.23.16.43:9000',
      apiUrl: 'http://oo.proxy.open-front.hand-china.com',
      // apiUrl: 'https://hzerotstf.saas.hand-china.com/onlyoffice',
      // callbackUrl: 'https://your-backend/save',
      // title: 'test.docx',
      user: {
        id: '13485',
        name: '吴云强',
      },
      // "lang": "zh-EN",
      "lang": "zh",
      events: {
        onDocumentReady: (e) => {
          const editor = ooRef.current.getEditor();
          window.ooEditor = editor;
          console.log({ editor });
          console.log('onDocumentReady', e);

          setTimeout(() => {
            
//             // 初始化添加文档批注
//              ooRef.current?.executeCommand('command', `
// (function()
// {
//               const factorList = ${JSON.stringify(factorList)};

              
// function findElementByHcid(parentElement, value, source) {
//   const elementCount = parentElement.GetElementsCount();
//   for (let i = 0; i < elementCount; i++) {
//     const ele = parentElement.GetElement(i);
//     const eleType = ele.GetClassType();

//     if (eleType === 'paragraph') { // paragraph
 
//       if(source){
//         let searchResult = ele.Search(source + value);
//         if(searchResult.length) {
//           searchResult = ele.Search(value);
//           if(searchResult.length) {
//             return searchResult[0];
//           }
//         }
//       } else {
//         const searchResult = ele.Search(value);
//         if(searchResult.length) {
//           return searchResult[0];
//         }
//       }

//     }

//     if(ele.GetElementsCount) {
//       let findElement = findElementByHcid(ele, value, source);
//       if (findElement) {
//         return findElement;
//       }
//     }
//   }
//   return null;
// }
//                const doc = Api.GetDocument();

// // let comments = doc.GetAllComments();
// let commentsReport = doc.GetCommentsReport();
// let comments = [];
// for (let userName in commentsReport) {
//   comments =  comments.concat(commentsReport[userName]);
// }

//               for (const factor of factorList) {
         
//                 const comment = factor.comment || '';
//                 if(!comment) {
//                   continue;
//                 }
//                 const value = factor.value || '';
//                 const source = factor.source || '';

//                 if(comments.find && comments.find(item => item.CommentMessage === comment && item.QuoteText === value)) {
//                   continue;
//                 }

//                const ele = findElementByHcid(doc, value, source);
//                if(ele) {
//                  Api.AddComment(ele, comment); 
//                }

//              }
// })();
//             `).then(console.log, console.error)

            // 隐藏模式切换按钮
            ooRef.current?.executeDomApi("window.parent.document.querySelector('[data-layout-name=\"header-editMode\"]').style.display = 'none'");
          }, 1000);

        },
        onDownloadAs: (e) => {
          console.log('onDownloadAs', e);
          const tempLink = document.createElement('a');
          tempLink.style.display = 'none';
          const fileUrl = typeof e.data === 'string' ? e.data : e.data.url;
          tempLink.href = fileUrl;
          // const downloadName = decodeURIComponent(fileName);
          // tempLink.setAttribute('download', downloadName);
          // tempLink.download = downloadName;
          // alert(decodeURIComponent(fileName));
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
          }
          // 挂载a标签
          document.body.appendChild(tempLink);
          tempLink.click();
          setTimeout(() => {
            document.body.removeChild(tempLink);
            // 释放blob URL地址
            window.URL.revokeObjectURL(fileUrl);
          }, 3000);
        },
        onRequestRefreshFile: (e) => {
          console.log('onRequestRefreshFile', e);
        },
        onRequestOpen: (e) => {
          console.log('onRequestOpen', e);
        },
        onRequestCreateNew: (e) => {
          console.log('onRequestCreateNew', e);
        },
        onDocumentStateChange: (e) => {
          console.log('onDocumentStateChange', e);
        },
      },
    };

  }, []);

  const iframeRef = useRef(null);

  useEffect(() => {

    const handleMessage = async (event) => {
      // 确保消息来源是可信的
      if (event.origin !== window.location.origin) {
        console.warn('Received message from untrusted origin:', event.origin);
        return;
      }
      // 处理接收到的消息
      // console.log('Message received from iframe:', event.data);
      const { type, hcid, cmd, value, originValue, source } = event.data;
      if (!type || !hcid) {
        return;
      }

      if(cmd === 'highlight') {
        // 高亮显示


//       await ooRef.current?.executeCommand('command', `
// (function()
// {
// let doc = Api.GetDocument();
// doc.SetTrackRevisions(true);
// })();
//             `).then(console.log, console.error)

      //  await ooRef.current?.executeMethod("SearchNext", [ // SearchAndReplace SearchNext
      //       {
      //           "searchString": '贾倩倩',
      //           "matchCase": false
      //       },
      //       true
      //   ]).then(console.log, console.error)


//         await ooRef.current?.executeMethod('PasteText', ['<?姓名?>']).then(console.log, console.error)


              await ooRef.current?.executeCommand('command', `
(function()
{
let doc = Api.GetDocument();
// doc.SetTrackRevisions(true);

if(!Api._stroeEles){
  Api._stroeEles = {};
}

// if(!Api._rps){
//   Api._rps = Object.values(Api.GetDocument().GetReviewReport()).reduce((a,b) => a.concat(b), []);
// }

const cValue = '${value}';
const source = '${source || ''}';
const oValue = '${originValue || value}';

function findElementByHcid(hcid, parentElement, value) {
  const elementCount = parentElement.GetElementsCount();
  for (let i = 0; i < elementCount; i++) {
    const ele = parentElement.GetElement(i);
    const eleType = ele.GetClassType();

    if (eleType === 'paragraph') { // paragraph
 
      if(source){
        let searchResult = ele.Search(source + value);
        if(searchResult.length) {
          searchResult = ele.Search(value);
          if(searchResult.length) {
            return searchResult[0];
          }
        }
      } else {
        const searchResult = ele.Search(value);
        if(searchResult.length) {
          return searchResult[0];
        }
      }

    }
    // if (eleType === 'run') { // range
    //   const runText = ele.GetText().trim();
    //   if(runText === value) {
    //     return ele.GetRange(0, ele.GetText().length);
    //   }
    //   if(runText.includes(value)) {
    //     const startIndex = runText.indexOf(value);
    //     const endIndex = startIndex + value.length;
    //     const range = ele.GetRange(startIndex, endIndex);
    //     return range;
    //   }
    // }

    if(ele.GetElementsCount) {
      let findElement = findElementByHcid(hcid, ele, value);
      if (findElement) {
        return findElement;
      }
    }
  }
  return null;
}

      const hcid = '${hcid}';
      let findElement = (oValue !== cValue) ? (findElementByHcid(hcid, doc, oValue + cValue) || findElementByHcid(hcid, doc, cValue + oValue)) : null;
      if(!findElement) {
        findElement = findElementByHcid(hcid, doc, cValue);
        Api._rps = Object.values(Api.GetDocument().GetReviewReport()).reduce((a,b) => a.concat(b), []);
        if(findElement && Api._rps.length) {
          const fParagraph = findElement.GetAllParagraphs()[0];
          const fRange = fParagraph.GetRange();
          const fPosStart = fRange.GetStartPos();
          const fPosEnd = fRange.GetEndPos();

          const changeLogIndex = Api._rps.findIndex(item => 
            {  
              if(item.Type !== 'TextRem' || item.Value !== oValue)
                return false;
              const r = item.ReviewedElement.GetRange(); 
              return (fPosStart === r.GetStartPos() && fPosEnd === r.GetEndPos()); 
            } 
          );
          if(changeLogIndex !== -1 && Api._rps[changeLogIndex +1]?.Type === 'TextAdd') {
            findElement = findElementByHcid(hcid, doc, oValue + Api._rps[changeLogIndex +1].Value)
          }
        }
      }
      if(!findElement && cValue !== oValue) {
        findElement = findElementByHcid(hcid, doc, oValue);
      }
      if (findElement) {

          if(Api._currentEle) {
            // Api._currentEle.GetRange().SetHighlight('none');
            // Api._currentEle.GetElement(0).GetRange().Select();
          }

          if(findElement.GetClassType() === 'range') {
            // findElement.SetHighlight('yellow');
            findElement.Select();
          } else {
            const range = findElement.GetRange()
            // range.SetHighlight('yellow');
            range.Select();
          }

          console.log('Found element with hc-id:', hcid);
          Api._currentEle = findElement;
          Api._stroeEles[hcid] = findElement;
      }

})();
            `).then(console.log, console.error)
      // ooRef.current?.executeMethod('PasteText', ['<?年龄?>']).then(console.log, console.error)

      }

      if(cmd === 'unhighlight') {
        // 取消高亮显示
        await ooRef.current?.executeCommand('command', `
(function()
{
if(!Api._currentEle){
  console.warn('没有选中元素，无法执行 unhighlight 命令');
  return;
}

          // const findElement = Api._currentEle;
          // if(findElement.GetClassType() === 'range') {
          //   findElement.SetHighlight('none');
          // } else {
          //   const range = findElement.GetRange()
          //   range.SetHighlight('none');
          // }
})();
            `).then(console.log, console.error)
      }

      if(cmd === 'AddComment') {
        console.log('AddComment', { type, hcid });
        // 添加评论
         await ooRef.current?.executeCommand('command', `
(function()
{
if(!Api._currentEle){
  console.warn('没有选中元素，无法执行 change 命令');
  return;
}
      const comment = '${value}';
      Api.AddComment(Api._currentEle, comment);
})();
            `).then(console.log, console.error)
      }

      if(cmd === 'change') {
 await ooRef.current?.executeCommand('command', `
(function()
{

if(!Api._currentEle){
  console.warn('没有选中元素，无法执行 change 命令');
  return;
}

if(!Api.asc_GetSelectedText()) {
  console.warn('没有选中内容，无法执行 change 命令');
  return;
}
      const newValue = '${value}';
      let doc = Api.GetDocument();
      doc.SetTrackRevisions(true);

      const cEleType = Api._currentEle.GetClassType();

      // if(cEleType === 'run') {
      //   // Api._currentEle.ClearContent();
      //   // Api._currentEle.AddText(newValue);

      //   const range = Api._currentEle.GetRange()
      //   // range.SetHighlight('yellow');
      //   range.Select();
      //   Api.pluginMethod_PasteText(newValue);
      // }

      if(cEleType === 'range') {
        // Api._currentEle.Select();
        debugger;
        Api._currentEle.Delete();
        let iPos = Api._currentEle.GetEndPos();
        const pendPos = Api._currentEle.GetAllParagraphs()[0].GetRange().GetEndPos();
        if(iPos > pendPos) {
          iPos = Api._currentEle.GetStartPos() + Api._currentEle.GetText().length;
        }
        Api.GetDocument().MoveCursorToPos(iPos);
        Api.pluginMethod_PasteText(newValue);
      }

      // Api._currentEle.SetDisplayedText(newValue);
      // Api._currentEle.ClearContent();
      // Api._currentEle.AddText(newValue);
      // Api._currentEle.Delete();
      // debugger; 
      // Api._currentEle.GetElement(0).GetRange().Select();
      // Api.Paste([newValue]);

      // doc.SetTrackRevisions(false);
      // Api._currentEle.GetRange().SetHighlight('none');

})();
            `).then(console.log, console.error)
      }


      // 这里可以根据 type 和 id 做进一步处理
    }

    window.addEventListener('message', handleMessage);

    return () => {
        window.removeEventListener('message', handleMessage);
    };

  }, [iframeRef.current]);

  const _onlyofficeControllerHtmlStr = React.useMemo(() => {

    return onlyofficeControllerHtmlStr.replace(
      '</body>',
      `<script>
        console.log('OnlyOffice Controller Loaded');

        const factorList = ${JSON.stringify(factorList)};

        let currentEleEditor = null;

        const originValueMap = {};

        factorList.forEach(factor => {
          const hcid = factor.id;
            if(!hcid) {
              return;
            }
            const value = factor.value || '';
            originValueMap[hcid] = value;
          });

        const listen = (e) => {
          const target = event.target;
          const hcid = target.getAttribute('hc-id');
          if(!hcid) {
            return;
          }
          const type = target.nodeName.toLowerCase();
          if(e.type === 'click') {
           const cValue = target.value || target.checked || (target.selectedOptions ? target.selectedOptions[0].value : '');

           if(!cValue) {
              return;
            }

           if(originValueMap[hcid] === undefined) {
            originValueMap[hcid] = cValue;
           }

           const source = factorList.find(item => item.id === hcid)?.source;

            window.parent.postMessage({
              type,
              hcid,
              cmd: 'highlight',
              originValue: originValueMap[hcid],
              source,
              value: cValue,
            }, '*');
            if(currentEleEditor) {
              currentEleEditor.removeEventListener('change', listen);
            }
            currentEleEditor = target;
            currentEleEditor.addEventListener('change', listen);
            currentEleEditor.addEventListener('blur', listen, { once: true });
          }

          if(e.type === 'blur') {
            window.parent.postMessage({
              type,
              hcid,
              cmd: 'unhighlight',
            }, '*');
          }

          if(e.type === 'change') {

            const newValue = target.value || target.checked || (target.selectedOptions ? target.selectedOptions[0].value : '');
            
            if(!newValue) {
              return;
            }
            window.parent.postMessage({
              type,
              hcid,
              cmd: 'change',
              value: newValue,
            }, '*');
          }

           if(e.type === 'dblclick') {
            const prompt = window.prompt('请输入评论内容');
            if(!prompt) {
              return;
            }
            window.parent.postMessage({
              type,
              hcid,
              cmd: 'AddComment',
              value: prompt,
            }, '*');
          }
        };

        window.addEventListener('click', listen);
        // window.addEventListener('dblclick', listen);

        // window.addEventListener('change', () => {
        //   const target = event.target;
        //   const hcid = target.getAttribute('hc-id');
        //   if(!hcid) {
        //     return;
        //   }
        //   const type = target.nodeName.toLowerCase();

        //   console.log('change', { type, hcid, value: target.value || target.checked || (target.selectedOptions ? target.selectedOptions[0].value : '') });


        //   // window.parent.postMessage({
        //   //   type,
        //   //   hcid,
        //   //   value: target.value || target.checked || (target.selectedOptions ? target.selectedOptions[0].value : ''),
        //   // }, '*');
        // });

      </script>
      </body>`
    );
   }, []);

  const changeOnlyReadMode = () => {
    ooRef.current?.executeDomApi("window.parent.document.querySelector('.btn-group   > ul.select-checked-items > li:nth-child(3)').click()").then(console.log, console.error);
  };

  const changeEditMode = () => {
    ooRef.current?.executeDomApi("window.parent.document.querySelector('.btn-group > ul.select-checked-items > li:nth-child(2)').click()").then(console.log, console.error)
  };

  const getSlectText = () => {
    return ooRef.current?.executeCommand('command', `Api.asc_GetSelectedText()`);
  };

  return (
    <>
      <div className='my-btn-box'>
        <button onClick={handleFileUpload}>导入文件</button>
        <button onClick={handleExportFile}>下载文件</button>
        {/* <button onClick={() => { 
          
          ooRef.current?.executeCommand('command', `
(function()
{
  return 'asfsdf';
})();
            `).then(console.log, console.error)

         }}>test2</button>
        <button onClick={() => { ooRef.current?.executeMethod('PasteText', ['<?年龄?>']).then(console.log, console.error) }}>
          test
        </button> */}
        <button
          onClick={() => { ooRef.current?.executeDomApi("window.parent.document.querySelector('#left-btn-comments').click()").then(console.log, console.error) }}
        >
          打开批注面报
        </button>
         <button
          onClick={changeEditMode}
        >
          切换审阅模式
        </button>
        <button
          onClick={changeOnlyReadMode}
        >
          切换查看模式
        </button>
        <button
          onClick={() => { ooRef.current?.executeMethod('SetDisplayModeInReview', ['original']).then(console.log, console.error) }}
        >
          切换显示模式到原始状态
        </button>        
        <button
          onClick={() => { ooRef.current?.executeMethod('SetDisplayModeInReview', ['final']).then(console.log, console.error) }}
        >
          切换显示模式到最终状态
        </button>      
        <button
          onClick={() => { ooRef.current?.executeMethod('SetDisplayModeInReview', ['edit']).then(console.log, console.error) }}
        >
          切换显示模式到修改状态
        </button>     
        <button
          onClick={async () => { const s = await getSlectText(); ooRef.current?.executeMethod('AcceptReviewChanges', [!s]).then(console.log, console.error) }}
        >
          同意审批
        </button>
        <button
          onClick={async () => { const s = await getSlectText(); ooRef.current?.executeMethod('RejectReviewChanges', [!s]).then(console.log, console.error) }}
        >
          拒绝审批
        </button>
         <button
          onClick={async () => { 
            const s = await getSlectText();
            if(!s) {
              console.warn('没有选中内容，无法执行 AddComment 命令');
              return;
            }
            const prompt = window.prompt('请输入评论内容');
            if(!prompt) {
              return;
            } 
            ooRef.current?.executeCommand('command', `
(function()
{
if(!Api._currentEle){
  console.warn('没有选中元素，无法执行 change 命令');
  return;
}
      const comment = '${prompt}';
      Api.AddComment(Api._currentEle, comment);
})();
            `).then(console.log, console.error)

           }}
        >
          添加批注
        </button>
        {/* <button onClick={handleEdiorHello}>Hello</button> */}
      </div>
      <div className='my-edit-box'>
        <div style={{ height: '100%', width: 'calc(100% - 200px)' }}>
          {documentUrl && (
            <OnlyOfficeEditor
              ref={ooRef}
              tokenConfig={tokenConfig}
              documentUrl={documentUrl}
              // key={documentUrl}
              config={config}
              onSave={(data) => {
                console.log('Document saved:', data);
                // 实现保存逻辑
              }}
              onError={(error) => console.error('Editor error:', error)}
              style={{ height: '80vh' }}
            />
          )}
        </div>
        <div style={{ height: '100%', width: '200px' }}>
          <iframe
            ref={iframeRef}
            srcDoc={_onlyofficeControllerHtmlStr}
            style={{ width: '100%', height: '100%' }}
            title="OnlyOffice Controller"  
          />            
        </div>
      </div>
    </>
  )
}

export default App
